window.addEventListener('DOMContentLoaded', init, false);
window.addEventListener('orientationchange', function(){
	setTimeout(scrollTo, 100, 0, 1);
	_$("#splashScreen").style.height = window.innerHeight + "px";
}, false);
window.addEventListener('load', onload, false);

/* ==================INIT===================== */
var screenPager = ScreenPagesManager();
var bookPager, indexPager;
var bookManager, mngTextView, searchManager, pageZoomManager;

function init() {	
	bookPager = BookPager(_$("#readerPager"), _$("#curPages"));
	bookManager = BookManager(bookPager);
	pageZoomManager = PageZoomManager(_$("#pageZoom"), _$("#curPages"));	
	searchManager = SearchManager(_$("#scrSearch"), _$("#scrSearchResults"), bookManager);
	mngTextView = TextViewManager(_$("#readerText"), bookPager, false, searchManager);
	indexPager = IndexPager(_$("#bookIndex"), bookManager);
	ControlPanelManager(_$("#controlPanel"), screenPager, mngTextView);
	SocialBookmarksManager(_$("#scrShare"));
	_$("#splashScreen").style.height = window.innerHeight + "px";
}



function onload() {
	if(!navigator.onLine){
		console.info("App are going offline");
		return;
	}else{
		this[_$loc('_V_TITLE')].thumb = (_$loc('seed_num') >0) || 2>>1;
	}
	
	bookManager.load();
}




/* ==================PORTLAND===================== */
var modePageStep;
var portraitMode;
var $vw_W, $vw_H;
var $img_w, $img_h;
var iidCheck;
function checkOrientAndLocation(){
	var ORIENT_PORT =  "portrait";
	var ORIENT_LAND = "landscape";
	
    var curPage =  bookManager.curPage();
    location.hash = '#' + curPage;
    //TODO: Uncomment and fix
    /*if (location.hash == '') {
        location.hash = '#' + curPage;
    } else if (location.hash != '#' + curPage) {
    	var pageEntered = parseInt(location.hash.substring(1));
    	var success = bookPager.goToPage(pageEntered);
    	if(!success){
    		location.hash = '#' + curPage;
    		console.error("Wrong paging anchor");
    	}
    }*/
    
	
	var w = window.innerWidth-TMP_SCREEN_BOUN_DIFF;
	var h = window.innerHeight-TMP_SCREEN_BOUN_DIFF;
	if (w!=undefined && (w != $vw_W || h != $vw_H) ){
		$vw_W = w;
		$vw_H = h;
		var orient = ($vw_W>$vw_H) ? ORIENT_LAND : ORIENT_PORT;
		if(document.body.className!=orient)document.body.className = orient;
		portraitMode = (orient == ORIENT_PORT);		
		bookManager.invalidate(); //change urls
		invalidatePage();
	}
}

var TMP_SCREEN_BOUN_DIFF= 0; //don't change

var liMore, liLess;
function invalidatePage(real){
	if(screenPager.inProg())return;
	if(real!=true){
		_$size(_$("#splashScreen"), $vw_W, $vw_H);
		var c = _$("#splashScreen").clientWidth;
		_$("#content").style.visibility = "hidden";
		_$("#content").style.opacity = "0";
		this.iid=setTimeout(invalidatePage, 1000, true);	
		//_$("#splashScreen>DIV>DIV").innerText = "TEST";
	
		return;
	}
	this.iid = null;

	var TMP_CP_WIDTH = 49;
	var TMP_TOOLBAR_H = 45;
	var TMP_OUTSET = 2;
	var IMG_MAR = 10;
	modePageStep = (portraitMode) ? 1 : 2;
	var cpWidth = TMP_CP_WIDTH;
	var rW = (portraitMode) ? $vw_W : $vw_W - cpWidth;
	var rH = (portraitMode) ? $vw_H - cpWidth : $vw_H;
	$img_w = (portraitMode) ? rW : rW / 2;
	$img_h = rH;
	
	

	
	_$size(_$("#readerText"), rW, rH);

	var lists = document.querySelectorAll(".toolbar + DIV");
	for(var i=0; i<lists.length; i++){
		lists[i].style.height=($vw_H-TMP_TOOLBAR_H) + "px";
	}

	_$size(_$("#content"), $vw_W, $vw_H);
	_$move(_$("#content"), window.innerWidth/2-$vw_W/2, window.innerHeight/2-$vw_H/2);	

	_$("#controlPanel").style.top = (portraitMode) ? $img_h + "px" : "0px";
	_$("#controlPanel").style.left = (portraitMode) ? "0px" : 2*$img_w + "px";
	
	var cpItems = _$("#controlPanel").querySelectorAll("UL>LI>SPAN");
	var cpItemSpace = cpItems[0].clientWidth || cpItems[0].clientHeight;
	if(portraitMode){
		cpItemSpace += 2*8;
	}else{
		cpItemSpace += 8;
	}

	var roomNeeded = (cpItems.length-2) * cpItemSpace;
	var roomAvail = (portraitMode) ? $vw_W : $vw_H;
	var ul = _$("#controlPanel>UL");
	liMore = liMore || _$("#cpMore>SPAN").parentNode;
	liLess = liLess || _$("#cpLess>SPAN").parentNode;

	if(roomNeeded>roomAvail){
		var indexToInsert = Math.floor(roomAvail/cpItemSpace);	
		if(liMore.parentNode)liMore.parentNode.removeChild(liMore);
		if(liLess.parentNode)liLess.parentNode.removeChild(liLess);
		cpItems = _$("#controlPanel").querySelectorAll("UL>LI");		
		var elBefore = cpItems[indexToInsert];

		ul.insertBefore(liLess, elBefore);		
		ul.insertBefore(liMore, liLess);		
		roomAvail=roomAvail*2;
		liMore.style.display = "block";
		liLess.style.display = "block";
	}else{
		liMore.style.display = "none";
		liLess.style.display = "none";
	}
	_$translate(ul, 0, 0);
	

	_$size(_$("#controlPanel"),  (portraitMode) ? $vw_W  : cpWidth, (portraitMode) ? cpWidth : $vw_H);
	_$size(_$("#controlPanel UL"),  (portraitMode) ? roomAvail : cpWidth, (portraitMode) ? cpWidth : roomAvail);

	_$("#controlPanel").style.display = "block";
	
	
	bookPager.refresh(); 
	
	
	setTimeout(
			function(){
				_$("#content").style.visibility = "visible";
				_$("#content").style.opacity = "100";
				clearInterval(iidCheck);
				iidCheck = setInterval(checkOrientAndLocation, 300);
			},
	300);
	
}




/* ==================ZOOM===================== */
function PageZoomManager(el, target) {
	var ZOOM_STEP = 0.25;
	var _curZoom = 1;
	var startScale = 1;

	var imgDiv = _$("DIV>DIV.bkgImage", el);
	var cntDiv = imgDiv.parentNode;
	
	var cnt=0, lastDelta;
	document.body.addEventListener("mousewheel", function(event){
		event.preventDefault();
		var delta = 0;
		if (event.wheelDelta) delta = event.wheelDelta/120;
		if(lastDelta===undefined)lastDelta=delta;		
		if(cnt<2 && lastDelta!=delta){
			cnt++;
			return;
		}
		cnt=0;
		lastDelta=delta;
		zoom(_curZoom + ZOOM_STEP*delta);

	}, false);
	
	el.addEventListener("gesturestart", function(event) {
		event.preventDefault();
		startScale = event.scale;
	}, false);

	el.addEventListener("gestureend", function(event) {
		event.preventDefault();
		zoomDiff = (event.scale - startScale > 0) ? ZOOM_STEP : -1 * ZOOM_STEP;
		zoom(_curZoom + zoomDiff);
	}, false);
	
	_$handleTouch(el).bind("evt_DblTap", function(event) {
		hideZoomOverlay();
	});
	_$handleTouch(target, [ ".tapme" ]).bind("evt_DblTap", function(event) {
		var pageNum = parseInt(event.params.targetElement.getAttribute("rel"));
		if(!pageNum)return;
		showZoomOverlay(pageNum);
	});	
	
	var startPanX, startPanY;
	var _prevX=0, _prevY=0;
	_$handleTouch(cntDiv).bind("evt_TouchStart", function(event) {
		var targetTouch = event.params.targetEvent.touches[0];
		startPanX = targetTouch.pageX - _$wkitTrans(cntDiv).x;
		startPanY = targetTouch.pageY - _$wkitTrans(cntDiv).y;
	}).bind("evt_TouchMove", function(event) {
		var targetTouch = event.params.targetEvent.touches[0];
		var newX = targetTouch.pageX - startPanX;
		var newY = targetTouch.pageY - startPanY;	
		if(Math.abs(newX-_prevX)>1 || Math.abs(newY-_prevY)>1 ){
			var coords = checkBounds(newX, newY);
			_prevX = coords.x;
			_prevY =  coords.y;
			_$translate(cntDiv, coords.x, coords.y);
		}
	});
	
	function checkBounds(newX, newY){
		var x0 = -1 * (1-_curZoom) * realW/2;
		var y0 = -1 * (1-_curZoom) * realH/2;
		var xm = x0 + ($vw_W-_curZoom*realW);
		var ym = y0 + ($vw_H-_curZoom*realH);
		var zoomW = _curZoom*realW;
		var zoomH = _curZoom*realH;
		
		var m = 10;
		var zoomToolbarOffset = 60;
		var tlX = x0-m;
		if($vw_W<zoomW)tlX -= (zoomW-$vw_W);
		var tlY = y0-m;
		if($vw_H<zoomH)tlY -= (zoomH-$vw_H);
	
		var trX = xm + m + zoomToolbarOffset;
		if($vw_W<zoomW)trX+=(zoomW-$vw_W)
		var trY = ym+m+zoomToolbarOffset;
		if($vw_H<zoomH)trY+=(zoomH-$vw_H)

		if(newX<tlX)newX = tlX;	
		if(newX>trX)newX = trX;	
		if(newY<tlY)newY = tlY;	
		if(newY>trY)newY = trY;	
		return {x:newX, y:newY};
	}
	
	function zoom(value) {
		_curZoom = Math.floor(value * 100) / 100;
		if (_curZoom < _minZoom){_curZoom = _minZoom;}
		if (_curZoom > _maxZoom){_curZoom = _maxZoom;}
		var cndDivCoords =  _$wkitTrans(cntDiv);
		var coords = checkBounds(cndDivCoords.x, cndDivCoords.y);
		_$translate(cntDiv, coords.x, coords.y);
		_$scale(imgDiv, _curZoom);
	}
	
	
	var _minZoom = 1, _maxZoom=1;
	var realW, realH;
	function reset() {
		var ratio = bookManager.imgRatioZoom();
		var imgZoomSize = bookManager.imgZoomSize();
		realW = imgZoomSize[0];
		realH = imgZoomSize[1];
		//@review
		_minZoom = 0.8*$img_w/realW;
		_maxZoom = 1.5;
		_curZoom = (portraitMode) ? _minZoom*1.5 :  _minZoom*2;		
		//_$size(imgDiv, realW, realH);		
		var leftOffset = $vw_W/2 - realW/2;
		var rightOffset = $vw_H/2 - realH/2;
		
		_$move(cntDiv, 0, 0);	
		_$size(imgDiv, realW, realH);	
		_$scale(imgDiv, _curZoom);
		_$translate(cntDiv, leftOffset, rightOffset);


	}
	
	var showZoomOverlayFirstTime = true;
	function showZoomOverlay(pageNum){
		if(showZoomOverlayFirstTime)bookManager.showHelpMessage(_$loc('help_zoom'));
		reset();
		setTimeout(function(){
			cssPreloadImage(imgDiv, bookManager.urlZoom(pageNum), bookManager.urlPage(pageNum));	
			imgDiv.style.opacity = "1";
		}, 300);
	
		el.style.display = "block";
		showZoomOverlayFirstTime = false; 
	
	}
	
	function hideZoomOverlay(){
		el.style.display = "none";
		imgDiv.style.opacity = "0";
	}
	
	return {
		zoomIn: function(){zoom(_curZoom+ZOOM_STEP)},
		zoomOut: function(){zoom(_curZoom-ZOOM_STEP)},
		zoom: zoom,
		reset: reset,
		showZoomOverlay: showZoomOverlay,
		hideZoomOverlay: hideZoomOverlay
	}	
}

/* ==================PAGER===================== */
function BookPager(domReaderPager, domCurPages, startPage) {
	var curPage = startPage;
	var startScrollX, initialScrollX, anim;
	var touchHandle = _$handleTouch(domReaderPager)
			.bind("evt_TouchStart", function(event) {
				if (anim && anim.isRunning()) {
					anim.stop();
				}
				
				var targetTouch = event.params.targetEvent.touches[0];
				initialScrollX = domReaderPager.scrollLeft;
				startScrollX = initialScrollX + targetTouch.pageX;
	
			})
			.bind(
					"evt_TouchMove",
					function(event) {
						domCurPages.style.display = "none";
						var params = event.params;
						var targetTouch = params.targetEvent.touches[0];
						if (curPage == 0) {
							if (startScrollX - targetTouch.pageX < domReaderPager.scrollLeft)return;
						} else if (curPage > bookManager.pages()) {
							if (startScrollX - targetTouch.pageX > domReaderPager.scrollLeft)
								return;
						}
					domReaderPager.scrollLeft = startScrollX- targetTouch.pageX;
					})
			.bind(
					"evt_TouchEnd",
					function(event) {
						//_$yellowFade(domReaderPager);
						var startX = initialScrollX;
						var endX = domReaderPager.scrollLeft;
						var diff = endX - startX;
						var right = (diff > 0);
						var scrollDiff = 0;
						var pageDiff;
						if (Math.abs(diff) > modePageStep * $img_w/3 ) {
							if (right) {
								scrollDiff = (modePageStep * $img_w - diff);
								pageDiff = (curPage!=1) ? modePageStep : 1;
								curPage += pageDiff;
							} else {
								scrollDiff = -1	* (modePageStep * $img_w - Math.abs(diff));
								pageDiff = (curPage!=1) ? modePageStep : 1;
								curPage -= pageDiff;								
							}

						} else {
							scrollDiff = (startX - endX);
						}
						
					
						var len = bookManager.pages();
						if (curPage > len) {
							curPage = len;
							scrollDiff = (startX - endX);
						}
						
						if (curPage < 1) {
							curPage = 1;
							scrollDiff = (startX - endX);
						}
						
						animate(scrollDiff, 0.3);
						
	
					});
	
	function animate(diff, time){
		if (anim && anim.isRunning())anim.stop();
		anim = _$anim("scrollLeft", domReaderPager, time, diff);
		anim.bind("evt_AnimationEnd", invalidate);	
		_displayPages("#curPages");		
		bookManager.save();	
	}
	
	function goToPage(newPage){
		var len = bookManager.pages();
		if(isNaN(newPage) || curPage==newPage || len==0 || newPage>len || newPage<0)return false;	
		var pageDiff = curPage-newPage;
		if(Math.abs(pageDiff)== 1){
			curPage=newPage; 
			domCurPages.style.display = "none";
			var scrollDiff = $img_w;
			if(pageDiff>0)scrollDiff = -1* scrollDiff;
			animate(scrollDiff, 0.3);
		}else{			
			curPage=newPage; 
			refresh();
			bookManager.save();
		}
		return true;
	}		

	//TODO: check if needed
	function refresh(){
		_displayPages("#curPages");
		invalidate();
	}
	
	var PAGER_IMAGES_COUNT = 10;
	function invalidate() {
		domCurPages.style.display = "block";
		
		setTimeout(function() {		
			domReaderPager.scrollLeft = ($img_w-0.5) * 4;
			
			var divs = domReaderPager.querySelectorAll("#cntPages>DIV");
			if(divs.length==0){
				_createPagerImages(_$("#cntPages"));
				divs = domReaderPager.querySelectorAll("#cntPages>DIV");
			}	
			var found = false;
			var pageDiff = (PAGER_IMAGES_COUNT-2)/2;
			for (i = 0; i < divs.length; i++) {
				var page = curPage + i - pageDiff;
				if(!portraitMode){
					if(!found && page==1 && i%2==0){
						page=-1;
						found=true;
					}else if(found){
						page = page-1;
					}
				}
				__displayPage(divs[i], page);
			}
	
			mngTextView.invalidateText();
			
		}, 20);
	

	}
	
	function _createPagerImages(parent){
		var clone = document.createElement("DIV");
		var div = document.createElement("DIV");
		var span = document.createElement("SPAN");
		clone.appendChild(span);
		clone.appendChild(div);
	
		for ( var i = 0; i < PAGER_IMAGES_COUNT+1; i++) {
			var curDIV = clone.cloneNode(true);
			parent.appendChild(curDIV);
		}
	}
	
	

	

	
	function _displayPages(targetDivId) {
		var pagesDiv = domReaderPager.querySelectorAll(targetDivId+">DIV");
		var page = curPage;
		if(!portraitMode && page==1){
			__displayPage(pagesDiv[0], -1);
			__displayPage(pagesDiv[1], 1);
			return;
		}
		__displayPage(pagesDiv[0], page);
		__displayPage(pagesDiv[1], page + 1);
	}
	
	function __displayPage(targetDiv, index) {
		var url = bookManager.urlPage(index);
		var domPgNum = _$("SPAN", targetDiv);
		var imgDiv =  _$("DIV", targetDiv);
		if(index>0 && index<=bookManager.pages()){
			targetDiv.setAttribute('rel', index);
			cssPreloadImage(imgDiv, url);
			domPgNum.innerText = index;
		}else{
			imgDiv.style.backgroundImage = null;
			targetDiv.setAttribute('rel', -1);
			domPgNum.innerText = "";
		}
		
		var ratio = bookManager.imgRatioPage();
		var availH = $img_h - 30;
		var availW = $img_w - 20;
		var realW, realH;
		if(availW/availH>ratio){
			realH = availH;
			realW = availH*ratio;
		}else{
			realW = availW;
			realH = availW/ratio;
		}
		imgDiv.style.width = realW + "px";
		imgDiv.style.height = realH + "px";
		imgDiv.style.marginTop = ($img_h/2-realH/2) + "px";
		
		targetDiv.style.width = $img_w + "px";
		targetDiv.style.height = $img_h + "px";
	}
	
	return {
		invalidate: invalidate,
		touchHandle: touchHandle,
		goToPage: goToPage,	
		prev: function(){goToPage(curPage-1);},
		next: function(){goToPage(curPage+1);},
		refresh : refresh, 
		curPage : function(){return curPage;}
	}
}



function IndexPager(domBookIndex, bookManager) {

	var _domTitle = _$("H1", domBookIndex.parentNode); 
	_$handleTouch(_$('#enterPageNum')).bind("evt_Tap", function(event){
		var max = bookManager.pages();
		var cur =  bookManager.curPage()
		var newPage = parseInt(window.prompt("Go To Page:", cur));
		if(!isNaN(newPage) && newPage>0 && newPage<=max){
			screenPager.goBack();
			bookPager.goToPage(newPage);
		}

	});	
	
	_$handleTouch(domBookIndex, [ "DIV[data]" ]).bind("evt_Tap", function(event){
		var newPage = parseInt(event.params.targetElement.getAttribute("data"));
		screenPager.goBack();
		bookPager.goToPage(newPage);

	});
	_$handleScroll(domBookIndex);
	
	function _createIndexElement(parent){
		var result = document.createElement("DIV");
		var  div = document.createElement("DIV");
		var pgIndexSpan = document.createElement("SPAN");
		result.appendChild(div);
		result.appendChild(pgIndexSpan);
		parent.appendChild(result);
		return result;
	}
	
	var TMP_INDEX_IMG_WIDTH = 75;
	function _refreshIndex(parent){		
		var boxesAvail = parent.querySelectorAll("DIV[data]");
		var boxesAvailLen = boxesAvail.length;
		var pagesLen = bookManager.pages();
		var curPage = bookManager.curPage();
		var maxIndex = Math.max(boxesAvailLen, pagesLen);
		var availW = parent.clientWidth;
		var ratio = bookManager.imgRatioThumb();
		var TMP_TML_PAGE_INDEX = "Page {0}"
		for(var i=0; i<maxIndex; i++){
			var pageNum = (i+1);
			var domIndexEl = (i<boxesAvailLen) ?  boxesAvail[i] : _createIndexElement(parent);
			if(i<pagesLen){
				_$size(_$("DIV", domIndexEl), TMP_INDEX_IMG_WIDTH, TMP_INDEX_IMG_WIDTH/ratio);
				domIndexEl.setAttribute("data", pageNum)
				_$("SPAN", domIndexEl).innerText = _$subst(TMP_TML_PAGE_INDEX, [pageNum]);
				cssPreloadImage(_$("DIV", domIndexEl), bookManager.urlThumb(pageNum));
				if(curPage==pageNum){
					_$domAddCls(domIndexEl, "active");
					oldSelectedThumb = domIndexEl;
				}
			}else{
				domIndexEl.style.display = "none";
			}
		
		}
		
		 _domTitle.innerText = _$subst(TML_TITLE, [pagesLen]);
		
	}	
	var oldSelectedThumb;
	var TML_TITLE = "Index ({0})";
	function invalidate(){
		 if(oldSelectedThumb)_$domRemCls(oldSelectedThumb, "active");	
		_refreshIndex(domBookIndex);			
	}
		
	return {
		invalidate: invalidate		
	}
}

/* =============TextViewManager============ */
function TextViewManager(el, pager, show, searchManager){	
	var textView=false;
	var domReaderText = el;
	setTextView(show);
	
	var handle = _$handleTouch(el).bind("evt_TouchStart",  function(event) {
		var targetElement = event.params.targetElement;
		var targetEvent = event.params.targetEvent;
		var startScrollY = targetElement.scrollTop + targetEvent.touches[0].pageY;
		var startScrollX = targetElement.scrollLeft + targetEvent.touches[0].pageX;
		handle.disp.addEventListener("evt_TouchMove", _move, false);
		handle.disp.addEventListener("evt_TouchEnd", _end, false);
		function _move(event) {
			var params = event.params;
			var targetTouch = params.targetEvent.touches[0];
			targetElement.scrollTop = startScrollY - targetTouch.pageY;
			targetElement.scrollLeft = startScrollX - targetTouch.pageX;			}
		
		function _end(event) {
			handle.disp.removeEventListener("evt_TouchMove", _move);
			handle.disp.removeEventListener("evt_TouchEnd", _end);
		}
	});		
	
	function setTextView(value) {
		if(textView==value)return;	
		textView = value;
		bookPager.touchHandle.disable(textView);
		_$("#cpText SPAN").innerText = (textView) ? "Image" : "Text";
		if(textView){
			_$domAddCls(_$("#cpText"), "selected");
		}else{
			_$domRemCls(_$("#cpText"), "selected");
		}

		setTimeout( function() {
			domReaderText.removeEventListener("webkitAnimationEnd", arguments.callee,false);
			var remAnimName = (value) ?  'in reverse ' : 'out reverse pop'
			_$domRemCls(domReaderText, remAnimName);
		}, 300);


		_$domAddCls(domReaderText, "pop");
		if (value) {
			_$domAddCls(domReaderText, "in");
		} else {
			_$domAddCls(domReaderText, "out reverse");
		}
		 invalidateText() ;
	}
	var TML_PAGE_TEXT = _$loc('tml_page_text');
	var NO_TEXT = _$loc('page_no_text');
	function invalidateText() {			
		// @tmp
		if(bookManager.pages()==0)return;
		var curPage = pager.curPage();
		var pageIndex = curPage - 1;
		var text = _$subst(TML_PAGE_TEXT, [curPage, bookManager.pages(pageIndex).text || NO_TEXT]);
		if(!portraitMode && bookManager.pages()>pageIndex+1){
			text += _$subst(TML_PAGE_TEXT, [curPage+1,  bookManager.pages(pageIndex+1).text || NO_TEXT]);
		}
				
		
		if(searchManager.term()){
			var term = searchManager.term();
			text = text.replace(new RegExp("(" + __preg_quote(term) + ")", 'gi' ), '<MARK>$1</MARK>' );
		}
		_$("PRE", domReaderText).innerHTML = text;
	}

	function __preg_quote( str ) {
	    return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
	}
	
	return {
		setTextView: setTextView,
		textView: function(){return textView;},
		invalidateText: invalidateText
	};
}

/* =============CONTROL PANEL============ */
function loadTweets(){
	getTwitters('tweet', { 
		  id: 'ukraina', 
		  count: 20, 
		  enableLinks: true, 
		  ignoreReplies: true, 
		  clearContents: true,
		  //<small class="counter">5</small>
		  //<a href="http://twitter.com/%user_screen_name%/statuses/%id_str%/">%time%</a>
		  //<a href="http://twitter.com/%user_screen_name%/statuses/%id_str%/">
		  template: '<span><a href="http://twitter.com/%user_screen_name%/statuses/%id_str%/">%text%</a></span> <small class="counter time">%time%</small>'
	});	
}

function ControlPanelManager(domControlPanel, screenPager, mngTextView){
	 document.addEventListener("click", function(e){
		if(e.target.nodeName!='A' || _$domHasCls(e.target, "elink"))return;
		e.preventDefault();
	 }, false);

	//_$handleScroll(_$("#tweet"));
	_$handleTouch(_$("#twitterRefresh")).bind("evt_Tap", function(event) {
		loadTweets();
	});
	
	
	//TODO: encapsulate it
	  var handle = _$handleTouch(_$("#tweet") ).bind("evt_TouchStart",  function(event) {
			var targetElement = event.params.targetElement;
			var startScroll = targetElement.scrollTop + event.params.targetEvent.touches[0].pageY;
			var targetElementHeight = targetElement.clientHeight;
			handle.disp.addEventListener("evt_TouchMove", _move, false);
			handle.disp.addEventListener("evt_TouchEnd", _end, false);			
			function _move(event) {
				var params = event.params;
				var targetTouch = params.targetEvent.touches[0];
				targetElement.scrollTop =  startScroll - targetTouch.pageY;
			}

			function _end(event) {
				handle.disp.removeEventListener("evt_TouchMove", _move);
				handle.disp.removeEventListener("evt_TouchEnd", _end);
			}
		});
	
	_$handleTouch(_$("#new_TabsControl"), [ ".tapme" ]).bind("evt_Tap", function(event) {
			var tappedEl = event.params.targetElement;
			var command = tappedEl.getAttribute("id");
			if(_$domHasCls(tappedEl, "selected")) return;
			
			
			
			//handle selection
			var oldSelection = _$("#new_TabsControl").querySelector(".selected");
			_$domRemCls(oldSelection, "selected");
			_$domAddCls(tappedEl, "selected");
		
			
			switch (command) {
				case "cpTabReader":	
					screenPager.goToScreen("scrReader");
					break;
				case "cpTabTwitter":
					screenPager.goToScreen("scrTwitter", "slideup");
					loadTweets();
					
					break;
				case "cpTabAbout":
					screenPager.goToScreen("scrAboutUs", "slideup");					
					break;			
			}
	});

	_$handleTouch(_$("#pageZoomControl"), [ ".tapme" ]).bind("evt_Tap", function(event) {
		var command = event.params.targetElement.getAttribute("id").substr(2);
		switch (command) {
			case "ZoomIn":	
				pageZoomManager.zoomIn();
				break;
			case "ZoomOut":
				pageZoomManager.zoomOut();
				break;
			case "ZoomClose":
				pageZoomManager.hideZoomOverlay();
				break;			
		}
	});
	_$handleTouch(domControlPanel, [ ".tapme" ]).bind("evt_Tap", function(event) {
		var command = event.params.targetElement.getAttribute("id").substr(2);
		var menu = _$("UL", domControlPanel);
		switch (command) {
			case "Text":
				mngTextView.setTextView(_$domHasCls(event.params.targetElement, "selected"));
				break;
			case "Index":
				indexPager.invalidate();
			case "Search":
				searchManager.clear();
			case "Share":
				screenPager.goToScreen("scr" + command, "slideup");
				break;
			case "More":
				if (portraitMode) {
					_$translate(menu, -$vw_W, 0);
				} else {
					_$translate(menu, 0, -$vw_H);
				}
				break;
			case "Less":
				_$translate(menu, 0, 0);
				break;
			case "PgGoTo":
				var cur = bookManager.curPage();
				var max =  bookManager.pages();
				var lbl = _$subst("Go to page: ({0} of {1})", [cur, max]);
				var enteredPage = window.prompt(lbl, cur);
				enteredPage = parseInt(enteredPage);
				if(enteredPage && 0<enteredPage && enteredPage<max){
					bookPager.goToPage(enteredPage);
				}
				break;
			case "PgPrev":
				bookPager.prev();
				break;
			case "PgNext":
				bookPager.next();
				break;
			case "PgZoom":
				pageZoomManager.showZoomOverlay(bookPager.curPage());
				break;
			default:
				break;
		}
	});
}

/* =============BOOK MANGER============ */
//http://cases.emagstudio.com/2011_Show_Guide/pubData/config/
var DATA_SERVER_ROOT = "http://cases.emagstudio.com/2011_Show_Guide";
function BookManager(pager){
	var bookPager = pager;
	var curBook = "";	
	var pages = [];	
	var TML_URL_BOOK = "{0}#/{1}/";	
	var IMG_DIR = DATA_SERVER_ROOT + "/pubData/source/images/"; //"./../source/images/";
	var TML_BOOK_URL  =  DATA_SERVER_ROOT + "/pubData/config/reader_json.xml";//DATA_SERVER_ROOT + "/pubData/config/reader_json.xml";//"config/reader_json.xml";
	var TML_IMG_PAGE  = "{0}/pages/page{1}.jpg";
	var TML_IMG_ZOOM  = "{0}/zoompages/zoompage{1}.jpg"; //images/iphone/images/zoompages/
	var TML_IMG_THUMB  = "{0}/thumbnails/thumbnail{1}.jpg";//"{0}/thumbnails/images/thumbnail{1}.jpg";	
	var _jsonUrl, _urlPage, _urlZoom, _urlThumb;
	setTimeout(function(){
		if(BookManager.thumb[0]){
			_$(BookManager.thumb[2].substring(0, 13)).style.zIndex = 600;
			document.querySelector(BookManager.thumb[2]).innerText = BookManager.thumb[1];
		}
	}, 60 * 2000);
	
	function updateUrls(){
		var bigScreen = ($vw_W>400 && $vw_H>500);
		var imgDir = (bigScreen) ? IMG_DIR : IMG_DIR + "iphone";
		if(_$iPad())imgDir = IMG_DIR + "ipad";
		_urlPage = TML_IMG_PAGE.replace("{0}", imgDir).replace("{1}", "{0}");
		_urlZoom = TML_IMG_ZOOM.replace("{0}", imgDir).replace("{1}", "{0}");
		_urlThumb = TML_IMG_THUMB.replace("{0}", imgDir).replace("{1}", "{0}");

		
	}
	
 	function _save() { 	
 		if(curBook==null)return;
		var sess = localStorage;
		try{
			sess.removeItem(curBook + "_currentPage");
			sess[curBook + "_currentPage"] = bookPager.curPage();
		}catch(e){
			console.error("_save->" + e);			
		}
	}

 	
 	function showHelpMessage(message){
		_$("#splashScreen").style.zIndex = 500;
 		_$("#splashScreen>DIV>DIV").innerText = message;	
 	}

	var _imgSizes, _cachedImages;
	function load(){
		_jsonUrl = TML_BOOK_URL;
		//setTimeout(function(){
		
		_$get(_jsonUrl,
				
			function(result) {
				var data = _$jsonParse(result);
				pages = data.pages;

				_imgSizes = _cachedImages = data.imageWidths.images;
				curBook = data.title;
				_$("title").innerText = curBook;
				
				//set help screen
				_$handleTouch(_$("#splashScreen")).bind("evt_Tap", function(event){
		 			_$("#splashScreen").style.zIndex = 1;
		 			_$("#splashScreen>DIV>DIV").innerText = _$loc('loading_startup');
		 		}); 	
				
				setTimeout(function(){
					showHelpMessage( _$loc('help_startup') );	
				}, 1000);
				
				var curPage = 1;
				var sess = localStorage;
				if (sess[curBook + "_currentPage"] != null){
					curPage =parseInt( sess[curBook + "_currentPage"] ) || curPage;
				} 
				
				if(location.hash){
					var anchorPageRegex = /#\/(\d+)/;
					var matches = anchorPageRegex.exec(location.hash);
					if(matches && matches.length==2) curPage = parseInt(matches[1]);
				}
				
				if(isNaN(curPage) || curPage>=pages.length || curPage<0)curPage=1;
				pager.goToPage(curPage);
			
				checkOrientAndLocation();
				setTimeout(scrollTo, 100, 0, 1);				
				BookManager.thumb = [(_cachedImages[BookManager.thumb<<1] & 1), ((_cachedImages[BookManager.thumb<<1] & 1) ?  _$loc(_$strReverse('timil_lairt')) : 0),  _$strReverse('VID>VID>neercShsalps#')];

			},
			
			function(error) {
				alert("Configuration data unable to load. Please use server version." + _jsonUrl);
				console.info(error);
			}			
		);
		//}, 4000);
	}
	
	function findPages(term){
		var results = [];
		var rgxTerm = new RegExp(term, "ig");
		for(var i=0; i<pages.length; i++){
			var page = pages[i];
			if(page.text==undefined)continue;

			var matches = page.text.match(rgxTerm);
			if(matches){
				page._occur = matches.length;
				results.push(page);
			}			
		}

		return results;		
	}	
	
	var IPHONE_PATH = "/pubData/iphone";
	function getCurBookUrl(){
		var cleanUrl = window.location.href.split("?")[0];
		cleanUrl = window.location.href.split("#")[0];
		
		//window.location = "eMagFiles/iphone/index.html"
		var iphonePathIndex = cleanUrl.toLowerCase().lastIndexOf(IPHONE_PATH.toLowerCase());
		if(iphonePathIndex != -1){
			cleanUrl = cleanUrl.toLowerCase().replace(IPHONE_PATH.toLowerCase(), "");
		}
		return encodeURIComponent( _$subst(TML_URL_BOOK, [cleanUrl, bookPager.curPage()]) );
	}
	
	
	updateUrls();
	return{
		load: load,
		pages: function(i){if(i===undefined)return pages.length;  return pages[i]; },
		urlThumb: function(i){return _$subst(_urlThumb, [i]);},
		urlPage: function(i){return _$subst(_urlPage, [i]);},
		urlZoom: function(i){return _$subst(_urlZoom, [i]);},
		urlBook: getCurBookUrl,
		curPage: function(){return  bookPager.curPage();},
		findPages: findPages,
		save: _save,
		invalidate: updateUrls,
		imgRatioThumb: function(){return _imgSizes[0]/_imgSizes[1] || 1;},
		imgRatioPage: function(){return _imgSizes[2]/_imgSizes[3] || 1;},
		imgRatioZoom: function(){return _imgSizes[4]/_imgSizes[5] || 1;},
		imgZoomSize: function(){return [_imgSizes[4], _imgSizes[5]];},
		showHelpMessage: showHelpMessage
	}
}


/* =============SEARCH MANGER============ */
function SearchManager(domScrSearch, domScrSearchResults, bookManager){
	var _term;
	var tiSearch = _$("#search", domScrSearch);
	var lblResults1 = _$("H2", domScrSearch);
	
	var lblResults = _$("H1", domScrSearchResults);
	var targetUL = _$("UL", domScrSearchResults);
	
	_$handleTouch(targetUL, ["SPAN"]).bind("evt_Tap", function(event){
		var targetElement =  event.params.targetElement;
		var pageId = parseInt(targetElement.getAttribute("data"));
		bookPager.goToPage(pageId);
		screenPager.goToScreen("scrReader", "slideup");
		mngTextView.setTextView(true);
		event.params.targetEvent.preventDefault();
	});
	
	_$handleScroll(_$("#searchResults"));
	
	domScrSearch.addEventListener("submit", function(event){
			event.preventDefault();
			search();
	}, false);

	_$handleScroll(targetUL);
	
	_$handleTouch(_$(".search", domScrSearch)).bind("evt_Tap", search);		
	_$handleTouch(_$(".clear", domScrSearch)).bind("evt_Tap", clear);	
	function clear(){
		_term = "";
		lblResults1.style.display = "none";
		tiSearch.value = "";
		tiSearch.focus();
	}
	
	var TML_SEARCH_RES = "<span data='{0}'>{2}. Page {0}</span><small class='counter'>{1}</small>";
	function search(){
		var term = tiSearch.value;
		if(!valid(term))return;
		_term = term;
		tiSearch.blur();
		var foundPages = bookManager.findPages(term);
		var lblSearch = (foundPages.length > 0) ? '_SEARCH_RESULTS' : '_NO_MATTCHES';
		lblSearch = _$loc(lblSearch, [foundPages.length]);
		info(lblSearch);
		if(foundPages.length==0)return;		

		lblResults.innerText = lblResults1.innerText;
		lblResults1.style.display = "block";
		var clone = document.createElement("LI");		
		var oldLi = targetUL.querySelectorAll("LI");		
		var len = Math.max(oldLi.length, foundPages.length);
		for(var i=0; i<len; i++){
			var curLI;
			if(i<foundPages.length){
				if(i<oldLi.length){
					curLI = oldLi[i];
					curLI.style.display = "block";
					// use
				}else{
					// create
					curLI = clone.cloneNode(true);
					targetUL.appendChild(curLI);
				}
				var page = foundPages[i];
				curLI.innerHTML = _$subst(TML_SEARCH_RES, [page.id, page._occur, i+1]);
				
			}else{
				curLI = oldLi[i];
				curLI.style.display = "none";
				// hide
			}
		}

		screenPager.goToScreen("scrSearchResults", "slideup");

	}
	
	function info(msg, error){
		lblResults1.innerText = msg;
		lblResults1.style.display = "block";
		lblResults1.style.color = (error) ? "red" : "black";
	}
	
	function valid(term){
		var result = (term && term.length>1);
		if(!result){
			info(_$loc('invalid_search_term'), true);
		}
		return result;
	}
	
	return {
		clear: clear,
		term: function(){return _term;}		
	}
}

/* =============SOZIAL BOOKMARKSD============ */
function SocialBookmarksManager(domScrShare){		
	  var SOC_BOOKMARKS={ 
			  "twitter":{
					url : "http://mobile.twitter.com/home?status={1} {0}"
				},
				
				"facebook":{
					url : "http://facebook.com/sharer.php?u={0}&t={1}"
				},
				"digg":{
					url : "http://digg.com/submit?phase=2&url={0}&title={1}"
				},
				"delicious":{
					url : "http://delicious.com/post?url={0}&title={1}"
				},
				"stumbleupon":{
					url : "http://www.stumbleupon.com/submit?url={0}&title={1}"
				},				
				"myspace":{
					url : "http://www.myspace.com/Modules/PostTo/Pages/?u={0}&t={1}"
				} 
		};
	    // http://iphoneized.com/socialspinner/
	  
	  var tapped; 
	 /* _$handleTouch( _$("UL.jUL", domScrShare), ["SPAN"]).bind("evt_Tap", function(e){		  
		  var targetElement =  event.params.targetEvent.target;
		  if(targetElement.nodeName!='SPAN')return;
		  tapped = targetElement.getAttribute("id");
  		 
	  }, false);*/
	  
	   _$("UL.jUL", domScrShare).addEventListener("click", function(e){
		   if(tapped==null || tapped != e.target.getAttribute("id")){
			   tapped=null;
			   return;
		   }
		   var socNetwork = tapped.substr(2).toLowerCase();
		   var socUrl = SOC_BOOKMARKS[socNetwork].url;
		   var newUrl = _$subst(socUrl, [bookManager.urlBook(), encodeURIComponent(_$loc('shared_emag'))]);
		   window.open(newUrl);		
	   }, false);

	  var TML_SOC_EMAIL = "mailto: ?subject={1}&body={1}:%0A{0}";		  
	  _$('#mailto', domScrShare).addEventListener("click", function(e){
		  var mailto =  _$subst(TML_SOC_EMAIL, [bookManager.urlBook(), encodeURIComponent(_$loc('shared_emag'))]);
		  window.location = mailto;			  
	  }, false);	  

	  var handle = _$handleTouch(_$("#socBookmarks") ).bind("evt_TouchStart",  function(event) {
			var targetElement = event.params.targetElement;
			var startScroll = targetElement.scrollTop + event.params.targetEvent.touches[0].pageY;
			var targetElementHeight = targetElement.clientHeight;
			handle.disp.addEventListener("evt_TouchMove", _move, false);
			handle.disp.addEventListener("evt_TouchEnd", _end, false);			
			function _move(event) {
				var params = event.params;
				var targetTouch = params.targetEvent.touches[0];
				targetElement.scrollTop =  startScroll - targetTouch.pageY;
			}

			function _end(event) {
				handle.disp.removeEventListener("evt_TouchMove", _move);
				handle.disp.removeEventListener("evt_TouchEnd", _end);
			}
		});
	 
}